<template>

 <!-- 查询表单 -->
 <el-form :model="searchForm" @submit.prevent="handleSearch">
      <el-form-item label="名称">
        <el-input v-model="searchForm.name" placeholder="请输入名称"></el-input>
      </el-form-item>
      <el-form-item label="年龄">
        <el-input v-model="searchForm.age" placeholder="请输入年龄"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
       <!-- 新增按钮 -->
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button type="primary" @click="queryPage">分页查询</el-button>
      </el-form-item>
    </el-form>

    <el-table 
        :data="tableData?.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
         class="fixed-height-table" 
          style="max-width: 99%;  max-height: 100%;  padding-left: 5%; padding-top: 10px; overflow-y: auto"  scrollbar=true   
          stripe="true"   >
      <!-- 动态生成列 -->
      <el-table-column
        v-for="header in headers"
        :key="header"
        :prop="header"
        :label="header"
        show-overflow-tooltip
         width="150"
      />
      <!-- 操作列 -->
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button @click="handleEdit(scope.row)">修改</el-button>
          <el-button @click="handleDelete(scope.row)" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="demo-pagination-block">
       <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[3,5,10,20]"
         layout=" sizes, prev, pager, next, jumper,total" :total="tableData?.length" />
     </div>

     <!-- 修改对话框 -->
  <el-dialog v-model="dialogVisible" title="修改数据" 
    :width="600"
    :height="400"
    :scrollable="true">
    <el-form :model="editForm" label-width="100px" style="max-height: 350px; overflow-y: auto;">
      <el-form-item
        v-for="header in headers"
        :key="header"
        :label="header"
        :prop="header"
      >
        <el-input v-model="editForm[header]" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer" style="display: flex; justify-content: center;">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 新增对话框 -->
  <el-dialog
    v-model="addDialogVisible"
    title="新增数据"
    :width="500"
    :height="400"
  >
    <el-form :model="addForm" label-width="100px" style="max-height: 350px; overflow-y: auto;">
      <el-form-item
        v-for="header in headers"
        :key="header"
        :label="header"
        :prop="header"
      >
        <el-input v-model="addForm[header]" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer" style="display: flex; justify-content: center;">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAdd">保存</el-button>
      </div>
    </template>
  </el-dialog>

  </template>

<script setup>
import { ref, onMounted,reactive,computed } from 'vue';
import axios from 'axios';
import { ElTable, ElTableColumn } from 'element-plus';
import Qs from 'qs'  // npm install qs  
import request from '../utils/request';

const tableData = ref([]);
const headers = ref([]);
const dialogVisible = ref(false);
const addDialogVisible = ref(false);
const editForm = reactive({});
const addForm = reactive({});

const searchForm = reactive({
  name: '',
  age: '',
});

const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);

function handleSearch() {
  filteredData.value = tableData.value.filter((row) => {
    return (
      (!searchForm.name || row.name.includes(searchForm.name)) &&
      (!searchForm.age || row.age.toString().includes(searchForm.age))
    );
  });
  currentPage.value = 1; // 重置当前页码为1
  total.value = filteredData.value.length;
}



onMounted(async () => {
    onSubmit();
});

//查询
function onSubmit(){
  debugger;
    request.post('/sys/dept/queryDept')
   .then((response) => {
    const data = response.data;
    tableData.value = data;
    headers.value = Object.keys(data[0]);
    total.value = data.length;
    })
   .catch((error) => {
      console.error(error.message);
    });

    
  }

  //新增
  function handleAdd() {
  addDialogVisible.value = true;
  Object.assign(addForm, {}); // 清空表单
}
 
const Page = reactive( {
    "pageNum": 1,
    "pageSize": 10,
    "dept_name": {
      "like": "部门"
    }
});
 
 
async function queryPage() {
  try {
    // 调用API添加数据
    const response = await request.post('/sys/dept/queryPage', Page);
    debugger;
  } catch (error) {
    console.log(error);
  }
}



function saveAdd() {
  // 调用API添加数据
  request.post('/sys/dept/addDept',Qs.stringify(addForm) )
        .then(function (response) {
          onSubmit();
          addDialogVisible.value = false;  
          ElMessage('新增成功');
           // 清空表单数据，不然重新新增还是原来的数据
              Object.keys(addForm).forEach(key => { 
                  });
      })
      .catch(function (error) {
        console.log(error);
      });

  // 假设API返回成功
  tableData.value.push(addForm); // 更新表格数据
  addDialogVisible.value = false;
}


function handleEdit(row) {
  // 将当前行的数据复制到editForm中
  Object.assign(editForm, row);
  dialogVisible.value = true;
}


         // 修改提交
 const saveEdit = (formEl) => {
    request.post('/sys/dept/updateDept',Qs.stringify(editForm) )
        .then(function (response) {
          onSubmit();
          dialogVisible.value = false;
          ElMessage('更新成功');
        })
        .catch(function (error) {
          console.log(error);
        });
     };

 

// 删除按钮的点击事件处理函数
function handleDelete(row) {
    request.post('/sys/dept/deleteDept',Qs.stringify(row) )
        .then(function (response) {
          onSubmit();
          dialogVisible.value = false;
          ElMessage('删除成功');
        })
        .catch(function (error) {
          console.log(error);
        });
    debugger;
}
</script>

<style>
/* 你可以在这里添加一些样式来美化表格 */
/* 设置表格单元格不自动换行 */
.el-table .cell {
  white-space: nowrap;
  overflow: hidden;
  /* text-overflow: ellipsis; */
}

.demo-pagination-block+.demo-pagination-block {
   margin-top: 10px;
 }

 .fixed-height-table {
  height: 580px;
  overflow-y: auto;
}

.demo-pagination-block+.demo-pagination-block {
   margin-top: 10px;
 }
  
 .demo-pagination-block .demonstration {
   margin-bottom: 16px;
 }
  
 .demo-pagination-block {
   padding: 15px;
   display: flex;
   justify-content: center;
 }
</style>